namespace SubhadraSolutions.Sharp.Logging.LogSubscribers
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Globalization;
    using System.IO;

    public abstract class AbstractTextLogSubscriber : AbstractLogSubscriber
    {
        #region Fields

        protected long _logItemIndex = 0;

        private string _linePadding = "\r\n";

        #endregion Fields

        #region Properties

        public string LinePadding
        {
            get { return _linePadding; }
            set
            {
                if (string.IsNullOrWhiteSpace(value))
                {
                    _linePadding = "\r\n";
                }
                else
                {
                    value = value.Trim().Trim('\r', '\n');
                    _linePadding = "\r\n" + value + "\r\n";
                }
            }
        }

        #endregion Properties

        #region Methods

        protected abstract TextWriter getTextWriter();

        protected override void publishLogs(IEnumerable<LogStoreItem> e)
        {
            try
            {
                TextWriter writer = getTextWriter();
                if (writer != null)
                {
                    publishLogs(writer, e);
                    writer.Close();
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
        }

        protected virtual void publishLogs(TextWriter writer, IEnumerable<LogStoreItem> e)
        {
            foreach (LogStoreItem logStoreItem in e)
            {
                _logItemIndex++;
                writer.Write(_logItemIndex.ToString(CultureInfo.InvariantCulture));
                writer.Write("\t");
                writer.Write(logStoreItem.ToString());
                writer.Write(_linePadding);
            }
        }

        #endregion Methods
    }
}